Page({
  data:{
    lists:[]
  },
  /* 从缓存中获取数据，有则设置data中的数据，没有就设置为空数组 */
  onLoad(){
    var lists = wx.getStorageSync('lists')
    if(lists){
      this.setData({
        lists
      })
    }else{
      wx.setStorageSync('lists', [])
    }
  },
  /* 获取搜索框的值并添加到数组中 */
  onSearch(event){
    var value = event.detail
    var lists = wx.getStorageSync('lists')
    var res = lists.every(item=>item.name!=value)  // 去重
    if(res && value.trim()){
      lists.push({
        name:value,
        state:false
      })
      wx.setStorageSync('lists', lists)
      this.setData({
        lists
      })
    }else{
      wx.showToast({
        title: '数据已经存在',
        icon: 'error'
      });
    }
  },
  /* 根据下标值来修改对应项的状态 */
  onChange(event){
    var value = event.detail
    var index = event.currentTarget.dataset.index
    var lists = wx.getStorageSync('lists')
    lists[index].state = value
    wx.setStorageSync('lists', lists)
    this.setData({
      lists
    })
  },
  /* 根据自定义name的值来筛选出对应的项 */
  onDelete(event){
    var lists = wx.getStorageSync('lists')
    var name = event.currentTarget.dataset.name
    var res = lists.filter(item=>item.name!=name)
    wx.setStorageSync('lists', res)
    this.setData({
      lists:res
    })
  }
})
